package jwt;

// 移除该注解，不然导致 maven 打包失败
//import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.SecretKey;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWT {

  public static void main(String[] args) {
    try {
      genKeyPair();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
  }

    /**
     * 随机生成密钥对
     *
     * @throws NoSuchAlgorithmException
     */
    public static void genKeyPair () throws NoSuchAlgorithmException {
      Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用于封装随机产生的公钥与私钥

      // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
      // 初始化密钥对生成器，密钥大小为96-1024位
      keyPairGen.initialize(4096, new SecureRandom());
      // 生成一个密钥对，保存在keyPair中
      KeyPair keyPair = keyPairGen.generateKeyPair();
      RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
      RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
      String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
      // 得到私钥字符串
      String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
      // 将公钥和私钥保存到Map
      keyMap.put(0, publicKeyString); //0表示公钥
      keyMap.put(1, privateKeyString); //1表示私钥
      for (Map.Entry<Integer, String> integerStringEntry : keyMap.entrySet()) {
        System.out.println(integerStringEntry.getKey());
        System.out.println(integerStringEntry.getValue());
      }
    }


  }
